import React, { useState } from "react";
import "./topbar.css";
import { 
  ExitToApp, 
  Search,
  Person,
  Business,
  Group
} from "@material-ui/icons";
import { 
  Avatar, 
  Menu, 
  MenuItem, 
  ListItemIcon, 
  ListItemText, 
  InputBase, 
  Paper,
  Divider,
  Tooltip
} from '@mui/material';
import { useNavigate } from "react-router-dom";

export default function Topbar() {
  const [anchorEl, setAnchorEl] = useState(null);
  const [searchQuery, setSearchQuery] = useState("");
  const navigate = useNavigate();
  
  // 模拟获取用户角色，实际应该从认证系统获取
  const isAdmin = localStorage.getItem("userRole") === "admin";

  const handleClick = (event) => {
    setAnchorEl(event.currentTarget);
  };

  const handleClose = () => {
    setAnchorEl(null);
  };

  const handleLogout = () => {
    // 先清除认证信息
    localStorage.clear();
    // 确保导航到登录页面
    navigate("/login", { replace: true });
    // 关闭菜单
    handleClose();
  };

  const handleSearch = (e) => {
    if (e.key === 'Enter') {
      // Handle search logic here
      console.log('Search query:', searchQuery);
    }
  };

  const handleLogoClick = () => {
    navigate("/");
  };

  const handleProfileClick = () => {
    navigate("/profile");
    handleClose();
  };

  const handleBusinessAdminClick = () => {
    navigate("/admin/businesses");
    handleClose();
  };

  const handleUserAdminClick = () => {
    navigate("/admin/users");
    handleClose();
  };

  function stringToColor(string) {
    let hash = 0;
    let i;
  
    /* eslint-disable no-bitwise */
    for (i = 0; i < string.length; i += 1) {
      hash = string.charCodeAt(i) + ((hash << 5) - hash);
    }
  
    let color = '#';
  
    for (i = 0; i < 3; i += 1) {
      const value = (hash >> (i * 8)) & 0xff;
      color += `00${value.toString(16)}`.slice(-2);
    }
    /* eslint-enable no-bitwise */
  
    return color;
  }

  function stringAvatar(name) {
    return {
      sx: {
        bgcolor: stringToColor(name),
        cursor: 'pointer'
      },
      children: `${name.split(' ')[0][0]}${name.split(' ')[1][0]}`,
    };
  }

  return (
    <div className="topbar">
      <div className="topbarWrapper">
        <div className="topLeft">
          <span className="logo" onClick={handleLogoClick}>Social Place Recommender System</span>
        </div>
        <div className="topCenter">
          <Paper
            component="form"
            sx={{
              p: '2px 4px',
              display: 'flex',
              alignItems: 'center',
              width: 400,
              borderRadius: '20px',
              boxShadow: '0 2px 4px rgba(0,0,0,0.1)'
            }}
          >
            <Search sx={{ color: 'action.active', ml: 1, mr: 1 }} />
            <InputBase
              sx={{ ml: 1, flex: 1 }}
              placeholder="Search..."
              value={searchQuery}
              onChange={(e) => setSearchQuery(e.target.value)}
              onKeyPress={handleSearch}
            />
          </Paper>
        </div>
        <div className="topRight">
          <Avatar 
            {...stringAvatar('Aditi Tanwar')} 
            className="topAvatar"
            onClick={handleClick}
          />
          <Menu
            anchorEl={anchorEl}
            open={Boolean(anchorEl)}
            onClose={handleClose}
            onClick={handleClose}
            PaperProps={{
              elevation: 0,
              sx: {
                overflow: 'visible',
                filter: 'drop-shadow(0px 2px 8px rgba(0,0,0,0.32))',
                mt: 1.5,
                minWidth: 200,
                '& .MuiAvatar-root': {
                  width: 32,
                  height: 32,
                  ml: -0.5,
                  mr: 1,
                },
              },
            }}
            transformOrigin={{ horizontal: 'right', vertical: 'top' }}
            anchorOrigin={{ horizontal: 'right', vertical: 'bottom' }}
          >
            <MenuItem onClick={handleProfileClick}>
              <ListItemIcon>
                <Person fontSize="small" />
              </ListItemIcon>
              <ListItemText>Profile Settings</ListItemText>
            </MenuItem>

            {isAdmin && (
              <>
                <Divider />
                <MenuItem onClick={handleBusinessAdminClick}>
                  <ListItemIcon>
                    <Business fontSize="small" />
                  </ListItemIcon>
                  <ListItemText>Business Management</ListItemText>
                </MenuItem>
                <MenuItem onClick={handleUserAdminClick}>
                  <ListItemIcon>
                    <Group fontSize="small" />
                  </ListItemIcon>
                  <ListItemText>User Management</ListItemText>
                </MenuItem>
              </>
            )}

            <Divider />
            <MenuItem onClick={handleLogout}>
              <ListItemIcon>
                <ExitToApp fontSize="small" />
              </ListItemIcon>
              <ListItemText>Logout</ListItemText>
            </MenuItem>
          </Menu>
        </div>
      </div>
    </div>
  );
}
